package com.bytedance.user.service.impl;

import com.bytedance.user.common.AIChatUtil;
import com.bytedance.user.common.JwtUtil;
import com.bytedance.user.common.RandomAvatarAndBgAndSi;
import com.bytedance.user.common.StatusCode;
import com.bytedance.user.mapper.UserMapper;

import com.bytedance.user.pojo.User;
import com.bytedance.user.properties.ZhiPuAiProperties;
import com.bytedance.user.request.UserLogAndRegRequest;
import com.bytedance.user.request.UserRequest;
import com.bytedance.user.respones.UserLogAndRegRespones;
import com.bytedance.user.respones.UserResponses;
import com.bytedance.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.web.client.RestTemplate;
import java.util.UUID;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RestTemplate restTemplate;


    @Autowired
    private ZhiPuAiProperties zhiPuAiProperties;

    @Transactional
    @Override
    public UserLogAndRegRespones register(UserLogAndRegRequest userLogAndRegRequest) {

//        校验数据库,用户username是否存在
        User user = userMapper.selectByUsername(userLogAndRegRequest.getUsername());
        UserLogAndRegRespones userLogAndRegRespones = new UserLogAndRegRespones();
        if (user != null) {
            //账号存在，不可以注册
            userLogAndRegRespones.setStatus_code(StatusCode.STATUS_FAIL);
            userLogAndRegRespones.setStatus_msg("账号存在，换一个账号！");
            return userLogAndRegRespones;
        }
        //用户注册,设置用户的基本info
        User user1 = new User();
        //用户默认名字
        String username = userLogAndRegRequest.getUsername();
        String defaultName = username + "_抖声用户_" + UUID.randomUUID().toString().split("-")[0];
        String password = userLogAndRegRequest.getPassword();
        String passwordMd5 = DigestUtils.md5DigestAsHex(password.getBytes());
        user1.setName(defaultName);
        user1.setAvatar(RandomAvatarAndBgAndSi.getRandomAvatar());
        user1.setBackground_image(RandomAvatarAndBgAndSi.getRandomBackGrounds());
        //调用AI生成随机文案
        String signature = AIChatUtil.getSignature(zhiPuAiProperties, restTemplate);
        user1.setSignature(signature);
        user1.setUsername(username);
        user1.setPassword(passwordMd5);
        user1.setFavorite_count(new Long(0));
        user1.setFollow_count(new Long(0));
        user1.setFollower_count(new Long(0));
        user1.setWork_count(new Long(0));
        user1.setTotal_favorited(new Long(0));
        log.info(user1.toString());
        userMapper.insertUser(user1);
        Long userId = user1.getId();
        //放入redis中
        ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set(userId, userId);
        log.info("打印userid" + userId);
        //将userid存入token
        String token = JwtUtil.createToken(userId);
        userLogAndRegRespones.setUser_id(userId);
        userLogAndRegRespones.setToken(token);
        userLogAndRegRespones.setStatus_code(StatusCode.STATUS_OK);
        userLogAndRegRespones.setStatus_msg("注册成功！");
        return userLogAndRegRespones;
    }

    @Override
    public UserLogAndRegRespones login(UserLogAndRegRequest userLogAndRegRequest) {
        String username = userLogAndRegRequest.getUsername();
        String password = userLogAndRegRequest.getPassword();
        String passwordMd5 = DigestUtils.md5DigestAsHex(password.getBytes());
        UserLogAndRegRespones userLogAndRegRespones = new UserLogAndRegRespones();
        //校验数据库
        User user = userMapper.selectByUsername(username);
        //账号是否存在
        if (user == null) {
            //账号不存在
            //不存在该用户
            userLogAndRegRespones.setStatus_code(StatusCode.STATUS_FAIL);
            userLogAndRegRespones.setStatus_msg("账号不存在！");
            return userLogAndRegRespones;
        }
        //账号存在，校验密码
        if (!(user.getPassword().equals(passwordMd5))) {
            //密码不相同
            userLogAndRegRespones.setStatus_code(StatusCode.STATUS_FAIL);
            userLogAndRegRespones.setStatus_msg("密码错误！");
            return userLogAndRegRespones;
        }
        //账号密码正确返回userid，生成携带userid的token
        Long userId = user.getId();
        String token = JwtUtil.createToken(userId);
        log.info("打印userid" + userId);
        ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set(userId, userId);
        userLogAndRegRespones.setToken(token);
        userLogAndRegRespones.setUser_id(userId);
        userLogAndRegRespones.setStatus_code(StatusCode.STATUS_OK);
        userLogAndRegRespones.setStatus_msg("登录成功！");
        return userLogAndRegRespones;

    }

    /**
     * 获取用户信息
     *
     * @param userRequest
     * @return
     */
    @Override
    public UserResponses getUserInfo(UserRequest userRequest) {
        Long userId = userRequest.getUser_id();
        /**
         * 获赞数量，作品数量，点赞数量应当从user表中查询
         */
        //查询对应的用户info ，从user表中查询
        User user = userMapper.selectUserInfo(userId);
        UserResponses userResponses = new UserResponses();
        /**
         * setIs_follow待处理
         */
        user.setIs_follow(false);
        userResponses.setUser(user);
        userResponses.setStatus_code(StatusCode.STATUS_OK);
        userResponses.setStatus_msg("获取用户信息成功！");
        log.info(userResponses.getUser().getAvatar());
        log.info(userResponses.getUser().getBackground_image());
        return userResponses;
    }

}
